package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {
    private static final String GET_OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";

    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static  final String ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appid}")
    private  String appid;

    @Value("${wechat.appSecret}")
    private String secret;
    @Override
    public String getOpenId(String code) {

        String result = HttpRequest.get(GET_OPENID_URL)
                .form("appid", appid)
                .form("secret", secret)
                .form("js_code", code)
                .form("grant_type", "authorization_code")
                .timeout(5000)
                .execute()
                .body();
        JSONObject jsonUtil = JSONUtil.parseObj(result);
        log.info("获取openId的结果"+jsonUtil);
        String openid=jsonUtil.getStr("openid");
        if (StrUtil.isEmpty(openid)){
            throw new ServiceException("获取openId失败！");
        }
        return openid;
    }

    @Override
    public String getPhone(String phoneCode) {
        String url = GET_PHONE_URL + getAccessToken();

        Map<String,String> map= Collections.singletonMap("code",phoneCode);
        String result =HttpRequest.post( url)
                .body(JSONUtil.toJsonStr(map))
                .timeout(5000)
                .execute()
                .body();
        System.out.println("result=" + result);
        JSONObject jsonObject=JSONUtil.parseObj(result);
        String phone = jsonObject.getByPath("phone_info.purePhoneNumber", String.class);
        if (StrUtil.isEmpty( phone)){
            throw new ServiceException("获取手机号失败！");
        }
        return phone;
    }

    /**
     * 获取微信·授权，有效期为两小时
     * 优化：:access_token缓存起来，设置有效时间为1小时
     * @return
     */
    private String getAccessToken() {

        String result = HttpRequest.get(ACCESS_TOKEN_URL)
                .form("grant_type", "client_credential")
                .form("appid", appid)
                .form("secret", secret)
                .timeout(5000)
                .execute()
                .body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        log.info("获取微信授权结果:{}",jsonObject);
        String accessToken = jsonObject.getStr("access_token");
        if (StrUtil.isEmpty(accessToken)){
            throw new ServiceException("获取微信授权失败！");
        }
        return accessToken;

    }
}
